<template>
    <div>
        <el-page-header @back="goBack" content="新增盘点单"></el-page-header>
        <div class="common_line"></div>
        <el-form ref="addForm" :model="addForm" :rules="rules" label-width="auto" style="margin-top: 20px;">
            <el-row>
                <el-col :span="12">
                    <el-form-item label="开单时间:" prop="orders_date">
                        <el-date-picker v-model="addForm.orders_date" type="date" format="yyyy-MM-dd" value-format="yyyy-MM-dd"
                            style="width: 240px" placeholder="请选择" clearable>
                        </el-date-picker>
                    </el-form-item>
                </el-col>
                <el-col :span="12" v-if="isAdmin">
                    <el-form-item label="经办人:">
                        <div class="choose_border" @click="chooseHandlerUsers('handler')">
                            <span style="color: #c0c4cf;" v-if="!handler_name">请选择</span>
                            <span>{{ handler_name }}</span>
                            <!-- <i class="el-icon-circle-close icon" @click.stop="clearValue('handler')"></i> -->
                        </div>
                    </el-form-item>
                </el-col>
                <el-col :span="12" v-else>
                    <el-form-item label="经办人:">
                        <div>{{ handler_name }}</div>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="24">
                    <el-form-item label="盈亏商品:">
                        <div class="choose" @click="showChooseGoods=true">选择商品</div>
                        <el-table :data="goods" border style="width: 100%" :key="tableKey">
                            <el-table-column label="序号" align="center" width="60" prop="index" />
                            <el-table-column label="图片" align="center" width="80">
                                <template slot-scope="scope">
                                    <img v-if="scope.row.imgUrl" :src="scope.row.imgUrl" style="width: 55px;height: 55px;" alt="">
                                </template>
                            </el-table-column>
                            <el-table-column label="商品名称" min-width="100" align="center">
                                <template slot-scope="scope">
                                    <div style="cursor: pointer;color: #0099ff;" @click="chooseProds">{{ scope.row.prod_name }}</div>
                                </template>
                            </el-table-column>
                            <el-table-column label="商品编号" align="center" prop="goods_no" />
                            <el-table-column label="库存数" min-width="80" align="center" prop="current_inventory_quantity" />
                            <el-table-column label="实际数" align="center">
                                <template slot-scope="scope">
                                    <input class="inner_input" @blur="numBlur($event, scope.row, 'real')" 
                                        style="width: 80px;" v-model="scope.row.real_inventory" placeholder="请输入">
                                </template>
                            </el-table-column>
                            <el-table-column label="单价(元)" align="center">
                                <template slot-scope="scope">
                                    <div style="display: flex;align-items: center;">
                                        <span>￥</span>
                                        <input class="inner_input" @blur="numBlur($event, scope.row, 'single')" 
                                            style="width: 80px;" v-model="scope.row.unit_price" placeholder="请输入">
                                    </div>
                                </template>
                            </el-table-column>
                            <el-table-column label="盈亏数" align="center" prop="ykCount" />
                            <el-table-column label="盈亏额" align="center" prop="ykAmount_name" />
                            <el-table-column label="操作" min-width="80" align="center" class-name="small-padding fixed-width">
                                <template slot-scope="scope">
                                    <el-button
                                        size="mini"
                                        type="text"
                                        @click="handleAdd"
                                        style="font-weight: bold;"
                                    >添加</el-button>
                                    <el-button
                                        size="mini"
                                        type="text"
                                        @click="handleRemove(scope.row)"
                                        style="font-weight: bold;"
                                    >移除</el-button>
                                </template>
                            </el-table-column>
                        </el-table>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="12">
                    <el-form-item label="盈亏总数:">
                        <div>{{ addForm.change_num }}</div>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="盈亏金额:">
                        <div>{{ '￥'+addForm.orders_fee }}</div>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="22">
                    <el-form-item label="备注:">
                        <el-input maxlength="200" show-word-limit type="textarea" :autosize="{ minRows: 2, maxRows: 6 }" v-model="addForm.remark" placeholder="请输入" clearable />
                    </el-form-item>
                </el-col>
            </el-row>
        </el-form>
        
        <bottom-btns
            Width="100%"
            MarginTop="30px"
            :buttons="buttonList"
            @superBtnClick="handleButtonClick"
        ></bottom-btns>

        <choose-product
            :showChooseProduct="showChooseGoods"
            :selectGoods="goods"
            @chooseOK="chooseOK"
            @hidden="showChooseGoods=false"
        ></choose-product>

        <!-- 选择经办人 -->
        <choose-user
            :showChooseUser="showChooseUserAlert"
            :selectUsers="selectedUsers.users"
            :title="selectedUsers.title"
            @chooseOK="chooseUserOK"
            @hidden="showChooseUserAlert=false"
        ></choose-user>
    </div>
</template>

<script>
import { getUserList } from "@/api/user";
import { listProduct, addStocktaking } from '@/api/product';
import bottomBtns from "@/components/bottomBtns";
import chooseProduct from "@/components/chooseProduct";
import chooseUser from "@/components/chooseUser";
const moment = require('moment')

export default {
    name: 'addStockTaking',
    components: {
        bottomBtns,
        chooseUser,
        chooseProduct
    },
    data() {
        return {
            showLoading: false,
            showChooseGoods: false,
            showChooseUserAlert: false,
            userType: '',
            isAdmin: false,
            tableKey: 1,
            addForm: {
                corp: '',
                orders_date: '',
                num_type: 1,
                fee_type: 1,
                orders_fee: 0, //盈亏金额
                change_num: 0, //盈亏总数
                remark: '',
                handler_user: '',
                goods: [],
            },
            goods: [],
            products: [],
            rules:{
                orders_date: [
                    { required: true, message: "请选择开单日期", trigger: "change" },
                ],
            },
            handler_name: '',
            handlersList: [],
            buttonList: [
                { name: '保存', type: 'commit', id:'1' },
                { name: '取消', type: 'cancel', id:'2' }
            ]
        }
    },
    props: {
        corpId: {
            type: Number
        }
    },
    computed: {
        selectedUsers() {
            let users = []
            if (this.addForm.handler_user){
                users = [{id: this.addForm.handler_user}]
            }
            let title = '选择经办人'
            return {
                users, title
            }
        }
    },
    mounted() {
        this.addForm.corp = this.corpId
        this.isAdmin = this.$store.state.isAdmin
        this.handler_name = this.$store.state.userInfo.username
        this.addForm.handler_user = this.$store.state.userInfo.id
        this.addForm.orders_date = moment().format('yyyy-MM-DD')
    },
    methods: {
        goBack() {
            this.$emit('hidden', '')
        },
        chooseHandlerUsers(type) {
            this.userType = type
            this.showChooseUserAlert = true
        },
        clearValue(type) {
            if (type == 'handler'){
                this.addForm.handler_user = ''
                this.handler_name = ''
            }
        },
        chooseUserOK(res) {
            if (this.userType == 'handler'){
                this.addForm.handler_user = res.length ? res[0].id : ''
                this.handler_name = res.length ? res[0].username : ''
            }
            this.showChooseUserAlert = false
        },
        numBlur(val, row, type) {
            let value = val.target.value
            value = value.replace(/[^0-9.]/g, ''); // 只允许数字和小数点
            const parts = value.split('.');
            if (parts.length > 2) {
                value = parts[0] + '.' + parts.slice(1).join(''); // 只取第一个小数点之前的部分
            }
            
            if (type == 'real') {
                row.real_inventory = value
                row.ykCount = this.$common.subtractFloat(value, parseFloat(row.current_inventory_quantity))
                row.ykAmount = this.$common.multiplyFloat(row.ykCount, row.unit_price)
                row.ykAmount_name = '￥'+row.ykAmount
            }else {
                row.unit_price = value
                row.ykAmount = this.$common.multiplyFloat(row.ykCount, value)
                row.ykAmount_name = '￥'+row.ykAmount
            }
                
            // 使用 this.$set 强制刷新视图
            this.$set(this.goods, this.goods.indexOf(row), row); 
            this.recalculate()
            this.tableKey++;
        },
        recalculate() {
            let total_count = 0, total_money = 0;
            this.goods.forEach(item => {
                item.ykCount = item.ykCount||0
                item.ykAmount = item.ykAmount||0
                total_count = this.$common.plusFloat(total_count, item.ykCount)
                total_money = this.$common.plusFloat(total_money, item.ykAmount)
            })
            this.addForm.change_num = total_count
            this.addForm.orders_fee = total_money
        },
        handleAdd() {
            this.goods.push({
                index:this.goods.length+1,imgUrl:'',prod_name:'',goods_no:'',unit_price:0,num:'',
                real_inventory:'',ykCount:'',ykAmount:'',ykAmount_name:'',current_inventory_quantity:''
            })
        },
        handleRemove(row) {
            function removeByIndexAndReindex(arr, indexToRemove) {
                // 使用 filter 方法过滤掉指定 index 的元素
                let newArray = arr.filter(item => item.index!== indexToRemove);
                // 遍历新数组，重新设置 index 属性
                for (let i = 0; i < newArray.length; i++) {
                    newArray[i].index = i + 1;
                }
                return newArray;
            }
            this.goods = removeByIndexAndReindex(this.goods, row.index)
        },
        chooseProds() {
            this.showChooseGoods = true
        },
        chooseOK(data) {
            console.log(data)
            this.goods = data.filter((item, index) => {
                item.index = index+1
                item.prod_name = item.name
                item.unit_price = item.unit_purchase_price?parseFloat(item.unit_purchase_price):0
                item.unit_price_name = '￥'+item.unit_price
                item.current_inventory_quantity = parseFloat(item.current_inventory_quantity)
                item.imgUrl = item.image_show?item.image_show.url:'https://anhuiyaoying.com/icon/default.png'
                return item
            })
            this.recalculate()
            this.showChooseGoods = false
        },
        handleButtonClick(item) {
            switch (item.id) {
                case '1':   // 保存
                    this.commit()
                    break;
                case '2':   // 取消
                    this.goBack()
                    break;
            
                default:
                    break;
            }
        },
        commit() {
            var that = this
            that.$refs['addForm'].validate(valid => {
                if(!valid) return
                
                this.addForm.goods = []
				this.goods.forEach(item => {
					this.addForm.goods.push({
						goods_id: item.id,
						change_num: item.ykCount,
						account_num: parseFloat(item.current_inventory_quantity),
						actual_num: item.real_inventory,
						num_type: item.ykCount>=0 ? 1 : 2,
						fee_type: item.ykAmount>=0 ? 1 : 2,
						unit_price: item.unit_price,
						total_price: item.ykAmount
					})
				})
				this.addForm.num_type = this.addForm.change_num>=0 ? 1 : 2
				this.addForm.fee_type = this.addForm.orders_fee>=0 ? 1 : 2
                addStocktaking(that.addForm).then(res => {
                    if (res.code == 200){
                        that.$message({
                            message: '操作成功',
                            type: 'success'
                        })
                        that.$emit('success')
                    }
                })
            })
        },
        handlerGoodsChange(value) {
            let [ id, index ] = value.split('&&')
            let chooseItem = {}
            this.products.forEach(item => {
                if (item.id === Number(id)) {
                    chooseItem = item
                }
            })
            this.goods.forEach(item => {
                if (item.index === Number(index)) {
                    item.prod_name = chooseItem.name
                    Object.assign(item, chooseItem)
                }
            })
            this.$forceUpdate()
            this.products = []
        },
        remoteMethodWithGoods(query, _index) {
            if (query !== '') {
                this.showLoading = true
                listProduct({
                    corp: this.addForm.corp,
                    search: query,
                    page: 1,
                    num: 999
                }).then(res => {
                    this.showLoading = false
                    this.products = res.data.data.good_list.filter(item => {
                        let cateName = item.category_name?('【'+item.category_name+'】'):''
                        item.label = cateName+item.name
                        item.value = item.id+'&&'+_index
                        item.unit_price = item.unit_purchase_price?parseFloat(item.unit_purchase_price):0
                        item.unit_price_name = '￥'+item.unit_price
                        item.current_inventory_quantity = parseFloat(item.current_inventory_quantity)
                        item.imgUrl = item.image_show?item.image_show.url:'https://anhuiyaoying.com/icon/default.png'
                        return item
                    });
                })
            } else {
                this.products = []
            }
        },
        // 选择经办人
        handlerPersonChange(value) {
            let [ id, username ] = value.split('&&')
            this.addForm.handler_user = id
            this.handler_name = username
        },
        remoteMethodWithHandler(query) {
            if (query !== '') {
                this.showLoading = true
                getUserList({
                    corp: this.addForm.corp,
                    username: query
                }).then(res => {
                    this.showLoading = false
                    this.handlersList = res.data.users.filter(item => {
                        item.label = item.username
                        item.value = item.id+'&&'+item.username
                        if (item.phone_no){
                            item.label += ('（'+item.phone_no+'）')
                        }
                        return item
                    });
                })
            } else {
                this.handlersList = []
            }
        }
    }
}
</script>

<style lang="less" scoped>
    @import '../../../style/mixin.less';
    
    .inner_input {
        width: 100px;
        padding: 8px 5px;
    }
    .choose {
        color: @blue;
        cursor: pointer;
        font-size: 14px;
        padding-left: 10px;
    }
</style>